var ws = require('ws');
const interest = require('../../models/interest');
var clientmap = new Map();
var server = new ws.Server({
    port: 8111,
});
var ping = 1
var pingexec = null;
server.on("connection", socketCliecnt_on_connection);


function socketCliecnt_on_connection(socketClient, req) {
    // console.log(this.id)
    let key = req.url.substr(1, req.url.length - 1)
    clientmap.set(key, { ws: socketClient, exist: ping });
    console.log("client " + key + " comming");
    // console.log(server.clients.entries())

    socketClient.on("close", socketClient_on_close(key));
    socketClient.on("message", socketClient_on_message);
    sendtoeveryone();

    if (clientmap.size == 1) {
        pingexec = setInterval(pingClient, 10 * 1000);
    }
}
function socketClient_on_message(message) {
    // console.log(this)
    let msg = JSON.parse(message)
    // if (message.toString() == "1") {
    //     pingClient()
    // }
    if (msg.type == "ping") {
        wsexist(msg)
    }
    // console.log(message)
}

function socketClient_on_close(key) {
    return () => {
        clientmap.delete(key);
        sendtoeveryone()
    }
}

function pingClient() {
    if (clientmap.size == 0) {
        clearInterval(pingexec)
        sendtoeveryone()
        return;
    }
    clientmap.forEach((value, key, mapself) => {
        console.log(key + ":" + value.exist)
        if (value.exist != ping) {
            clientmap.delete(key)
        }
    })
    ping = ping == 1 ? 0 : 1
    clientmap.forEach((value, key, mapself) => {
        // value.ws.send("ping" + ping)
        value.ws.send(
            JSON.stringify({
                type: "ping",
                value: ping
            })
        )
    })
    console.log("ping:" + clientmap.size)
    sendtoeveryone()

}

function wsexist(msg) {
    let source_temp = clientmap.get(msg.id)
    clientmap.set(msg.id, { ws: source_temp.ws, exist: parseInt(msg.pingvalue) })
}

function sendtoeveryone(msg) {
    let temp = clientmap.size;
    server.clients.forEach((value) => {
        value.send(JSON.stringify({
            type: "usercount",
            value: "当前用户数：" + temp
        }))
    })
}

module.exports = async (ctx, next) => {
    ctx.state.socketClientMap = clientmap;
    ctx.state.socketServer = server;
    await next();
}

// function websocket_add_listener(client_sock){
//     //close事件
//     client_sock.on("close",function(){
//         console.log("client close");
//         console.log(server.clients)
//     });

//     //error事件
//     client_sock.on("error",function(err){
//         console.log("client error",err);
//     });

//     client_sock.on("message",function(data){
//         console.log(data.toString());
//         client_sock.send("Thand you!!!");
//     })
// }

// function on_server_client_comming(client_sock,req){
//     console.log("client comming");
//     console.log(client_sock)
//     console.log(req)

//     // server.clients.keys()
//     websocket_add_listener(client_sock);
// }

// server.on("connection",on_server_client_comming);

// function on_server_headers(data){
// console.log(data)
// }

// server.on("headers",on_server_headers);